//
//  WYMessageController.m
//  CirclePush
//
//  Created by admin on 2018/4/17.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "WYMessageController.h"
#import "WYMessageCell.h"
#import "WYMessageModel.h"
#import "UITableView+FDTemplateLayoutCell.h"
@interface WYMessageController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)NSMutableDictionary *heightDict;
@end

@implementation WYMessageController
-(NSMutableDictionary *)heightDict
{
    if (!_heightDict) {
        _heightDict = [[NSMutableDictionary alloc]init];
    }
    return _heightDict;
}

-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray =[[NSMutableArray alloc]init];
    }
    
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self loadData];
}
-(void)loadData
{
    WEAKSELF
    [WYHttpServer getSystemMessageWithPageNum:@"1" WithPageSize:@"10" SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        
        if (success) {
            if ([WYMessageModel getMessageModelFromJson:response[@"result"]].count) {
                
                [weakSelf.dataArray addObject:[WYMessageModel getMessageModelFromJson:response[@"result"]]];
                [weakSelf.tableView reloadData];
                
                
            }
            
            
        }
        
        
        
    }];
    
    
    
    
}


-(void)setupUI
{
    [self initTopBarWithTitle:@"系统消息"];
    [self addLeftButton:[UIImage imageNamed:@"return"] width:0 height:0];
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"WYMessageCell" bundle:nil] forCellReuseIdentifier:@"WYMessageCell"];
//   self.tableView.estimatedRowHeight = 200.0f;//推测高度，必须有，可以随便写多少
//   self.tableView.rowHeight =UITableViewAutomaticDimension;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray[section] count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WYMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WYMessageCell" forIndexPath:indexPath];
   WYMessageModel *model =self.dataArray[indexPath.section][indexPath.row];
    cell.model = model;
    NSString *url = model.image;
    //[self configureCell:cell atIndexPath:indexPath];
    [cell setSelectionStyle:(UITableViewCellSelectionStyleNone)];
    [cell.messageImageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:nil options:SDWebImageRetryFailed completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (image.size.height) {
            /**  < 图片宽度 >  */
            CGFloat imageW = [UIScreen mainScreen].bounds.size.width - 2 * 8;
            /**  <根据比例 计算图片高度 >  */
            CGFloat ratio = image.size.height / image.size.width;
            /**  < 图片高度 + 间距 >  */
            CGFloat imageH = ratio * imageW + 15;
            /**  < 缓存图片高度 没有缓存则缓存 刷新indexPath >  */
            if (![[self.heightDict allKeys] containsObject:@(indexPath.row)]) {
                [self.heightDict setObject:@(imageH) forKey:@(indexPath.row)];
                [self.tableView beginUpdates];
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                [self.tableView endUpdates];
            }
        }
    }];
    
    
    
    return cell;
}
//- (void)configureCell:(WYMessageCell *)cell atIndexPath:(NSIndexPath *)indexPath {
//    WYMessageModel *model =self.dataArray[indexPath.section][indexPath.row];
//   // [cell setModel:model];
//  //  cell.fd_enforceFrameLayout = NO; // Enable to use "-sizeThatFits:"
//    cell.model = model;
//}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WYMessageModel *model =self.dataArray[indexPath.section][indexPath.row];
    return [[self.heightDict objectForKey:@(indexPath.row)] floatValue]+40 + [self heightForString:model.message andWidth:kScreenWidth-20];
    
    
//    return [tableView fd_heightForCellWithIdentifier:@"WYMessageCell" cacheByIndexPath:indexPath configuration:^(WYMessageCell *cell) {
//        [self configureCell:cell atIndexPath:indexPath];
//    }];
}
//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return 250;
//}



- (float) heightForString:(NSString *)value andWidth:(float)width{
    //获取当前文本的属性
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:value];
   // _text.attributedText = attrStr;
    NSRange range = NSMakeRange(0, attrStr.length);
    // 获取该段attributedString的属性字典
    NSDictionary *dic = [attrStr attributesAtIndex:0 effectiveRange:&range];
    // 计算文本的大小
    CGSize sizeToFit = [value boundingRectWithSize:CGSizeMake(width - 13.0, MAXFLOAT) // 用于计算文本绘制时占据的矩形块
                                           options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading // 文本绘制时的附加选项
                                        attributes:dic        // 文字的属性
                                           context:nil].size; // context上下文。包括一些信息，例如如何调整字间距以及缩放。该对象包含的信息将用于文本绘制。该参数可为nil
    return sizeToFit.height + 16.0;
}
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]init];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.frame = CGRectMake(0, NavHeight, kScreenWidth, kScreenHeight-NAV_HEIGHT);
        _tableView.tableFooterView = [[UIView alloc]init];
    }
    return _tableView;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
